package com.freecloud.bitorrent.domain.server.command;

import com.freecloud.bitorrent.common.util.NodeIdUtil;
import com.freecloud.bitorrent.constant.LocalNodeConstant;
import com.freecloud.bitorrent.convert.BitTorrentConvert;
import com.freecloud.bitorrent.demo.bo.FindNodeRequest;
import com.freecloud.bitorrent.demo.bo.FindNodeResponse;
import com.freecloud.bitorrent.demo.bo.RequestMessage;
import com.freecloud.bitorrent.demo.bo.ResponseMessage;
import com.freecloud.bitorrent.domain.server.support.DhtCommand;
import com.freecloud.bitorrent.domain.server.support.DhtEncode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: maomao
 * @Date: 2022/7/23 4:43 PM
 */
@Slf4j
@Component("find_node")
public class FindNodeCommand implements DhtCommand, DhtEncode {

    /**
     * 暂时只模拟存货，不对外边返回数据
     *
     * @param requestMessage
     * @return
     */
    @Override
    public ResponseMessage response(RequestMessage requestMessage) {
        log.info("find_node requestMessage : {}", requestMessage);
        ResponseMessage responseMessage = BitTorrentConvert.INSTANCE.request2Response(requestMessage);
        responseMessage.setResult(new FindNodeResponse(LocalNodeConstant.ip));
        return responseMessage;
    }

    @Override
    public Map<String, Object> encode(RequestMessage requestMessage) {
        Map<String, Object> map = new HashMap<>();
        map.put("t", requestMessage.getTransactionId().getBytes());
        map.put("y", requestMessage.getMessageType().getValue());
        map.put("q", requestMessage.getQuery().getValue());
        Map<String, Object> args = new HashMap<>();
        args.put("id", LocalNodeConstant.ip.equals(requestMessage.getArguments().getId()) ? LocalNodeConstant.nodeId :
            NodeIdUtil.randSelfNodeId(requestMessage.getArguments().getId()));
        args.put("target", LocalNodeConstant.ip.equals(((FindNodeRequest)requestMessage.getArguments()).getTarget()) ?
            LocalNodeConstant.nodeId :
            NodeIdUtil.randSelfNodeId(((FindNodeRequest)requestMessage.getArguments()).getTarget()));
        map.put("a", args);
        return map;
    }
}
